package com.ramblingcoder.bc2.server.tool.update;

import java.io.IOException;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Comparator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.ramblingcoder.bc2.server.tool.update.R;
import com.ramblingcoder.bc2.server.tool.update.commands.SupportingFunctions;
import com.ramblingcoder.bc2.server.tool.update.exceptions.InvalidArguments;
import com.ramblingcoder.bc2.server.tool.update.exceptions.LogInRequired;
import com.ramblingcoder.bc2.server.tool.update.objects.InfoShare;
import com.ramblingcoder.bc2.server.tool.update.objects.Server;

public class BC2ServerChoice extends Activity implements OnItemSelectedListener, OnClickListener, OnCheckedChangeListener {
	//Variables-----\
	private static boolean loginEncrypted = true;
	
	private Spinner serverChoices = null;
	private Server[] servers = null;
	
	private Button open = null;
	private Button delete = null;
	private Button edit = null;
	private CheckBox encrypt = null;

	private String serverChoicesComplete;
	private SharedPreferences settings;
	//Variables-----/
	
	//Initializer-----\
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.serverchoice);
        settings = getSharedPreferences("BC2ServerTool", 0);
        
        serverChoices = (Spinner) findViewById(R.id.serverchoices);
        open = (Button) findViewById(R.id.serveropen);
        delete = (Button) findViewById(R.id.serverdelete);
        edit = (Button) findViewById(R.id.serveredit);
        encrypt = (CheckBox) findViewById(R.id.serverencrypt);

        populateChoices();

    	serverChoices.setOnItemSelectedListener(this);
    	open.setOnClickListener(this);
    	delete.setOnClickListener(this);
    	encrypt.setOnCheckedChangeListener(this);
    	edit.setOnClickListener(this);
	}
	
	private void populateChoices() {
		serverChoicesComplete = settings.getString("serverChoices", "");
		
		servers = Server.parseServer(serverChoicesComplete);
		
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        
		Arrays.sort(servers, new Comparator<Server>() {
			public int compare(Server a, Server b) {
				return a.getDisplay().compareTo(b.getDisplay());
			}
		});
		
        for (Server server : servers) 
        	adapter.add(server.getDisplay());
        
        adapter.add("New");
        
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	
    	serverChoices.setAdapter(adapter);
	}
	//Initializer-----/
	
	//Processes-----\
	private void openServerCreation(final Server editServer) {
		final Dialog addServerDialog = new Dialog(this);
		addServerDialog.setContentView(R.layout.serveradd);
		
		if (editServer == null)
			addServerDialog.setTitle("Add Server");
		else
			addServerDialog.setTitle("Edit Server");
        
        Button confirm = (Button) addServerDialog.findViewById(R.id.serversave);
        Button cancel = (Button) addServerDialog.findViewById(R.id.serverexit);

        final TextView name = (TextView) addServerDialog.findViewById(R.id.servername);
        final TextView ip = (TextView) addServerDialog.findViewById(R.id.serverip);
        final TextView port = (TextView) addServerDialog.findViewById(R.id.serverport);
        final TextView pass = (TextView) addServerDialog.findViewById(R.id.serverpass);
        
        if (editServer != null){
	        name.setText(editServer.getName());
	        ip.setText(editServer.getIp());
	        port.setText(editServer.getPort()+"");
	        pass.setText(editServer.getPass());
        }
        
    	confirm.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (editServer != null)
					servers[serverChoices.getSelectedItemPosition()] = null;
				
				Server server = new Server(name.getText().toString(), ip.getText().toString(), port.getText().toString(), pass.getText().toString());
		        
				serverChoicesComplete = Server.compileServer(servers, server);
				
				settings.edit().putString("serverChoices", serverChoicesComplete).commit();
				
				finish();
				startActivity(new Intent(BC2ServerChoice.this, BC2ServerChoice.class));
			}
		});
        
        cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				addServerDialog.dismiss();
			}
		});
		
        addServerDialog.show();
	}
	
	private void deleteSelectedServer() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setMessage("Delete " + servers[serverChoices.getSelectedItemPosition()].getDisplay());
		
		builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				servers[serverChoices.getSelectedItemPosition()] = null;
				
				serverChoicesComplete = Server.compileServer(servers);
				
				settings.edit().putString("serverChoices", serverChoicesComplete).commit();
				
				finish();
				
				startActivity(new Intent(BC2ServerChoice.this, BC2ServerChoice.class));
			}
		});
		
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {}
		});
		
		AlertDialog dialog = builder.create();
		
		dialog.show();
	}
	//Processes-----/
	
	//Events-----\
	public void onClick(View v) {
		if (v.getId() == R.id.serveropen){
			if (serverChoices.getSelectedItem().toString().equalsIgnoreCase("new"))
				openServerCreation(null);
			else {
				try {
					if (InfoShare.initializeServer(servers[serverChoices.getSelectedItemPosition()])){
						ChatView.clearChat();
						finish();
						startActivity(new Intent(this, PlayerView.class));
					} else
						SupportingFunctions.showMessage(this, "Server Login", "The login information provided failed. No connection made.");
				} catch (UnknownHostException e) {
					SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
				} catch (NoSuchAlgorithmException e) {
					SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
				} catch (IOException e) {
					SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
				} catch (InvalidArguments e) {
					SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
				} catch (LogInRequired e) {
					SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
				}			
			}
		} else if (v.getId() == R.id.serverdelete){
			if (serverChoices.getSelectedItem().toString().equalsIgnoreCase("new"))
				return;
			
			deleteSelectedServer();
		} else if (v.getId() == R.id.serveredit){
			if (serverChoices.getSelectedItem().toString().equalsIgnoreCase("new"))
				return;
			
			openServerCreation(servers[serverChoices.getSelectedItemPosition()]);
		}
	}
	
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		loginEncrypted = isChecked;
	}

	public void onItemSelected(AdapterView<?> arg0, View v, int arg2, long arg3) {
		if (serverChoices.getSelectedItem().toString().equalsIgnoreCase("new"))
			openServerCreation(null);
	}
    
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        	finish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
	
	public void onNothingSelected(AdapterView<?> arg0) {}
	//Events-----/
	
	//Getters/Setters-----\
	public static boolean isLoginEncrypted() {
		return loginEncrypted;
	}
	//Getters/Setters-----/
}
